package com.cmii.sjw.department.control.jsc.constant;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author jfh
 * @Date 2025年09月15日 15:45
 */
@Slf4j
@Component
public class StreamResponseHandler {

//    @Autowired
//    private QARecordChunkMapper qaRecordChunkMapper;

    /**
     * 处理流式响应并记录
     */
    public String handleStreamResponse(Long recordId, InputStream inputStream, SseEmitter emitter) throws IOException {
        StringBuilder fullResponse = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        int chunkOrder = 1;

        while ((line = reader.readLine()) != null) {
            log.info("recv - {}", line);
            // 解析流式响应中的数据块
            if (line.startsWith("data:")) {
                String jsonData = line.substring(5).trim();
                try {
                    JSONObject jsonObject = JSONObject.parseObject(jsonData);
                    String content = parseContentFromStreamData(jsonObject);
                    if (content != null && !content.isEmpty()) {
                        fullResponse.append(content);

                        // 实时发送内容给客户端
                        if (emitter != null) {
                            try {
//                                emitter.send(SseEmitter.event().name("message").data(content));
                                emitter.send(SseEmitter.event().data(line));
                            } catch (IOException e) {
                                log.error("发送SSE消息失败", e);
                                // 继续处理其他数据
                            }
                        }

                        // 记录每个内容片段
//                        QARecordChunk chunk = new QARecordChunk();
//                        chunk.setRecordId(recordId);
//                        chunk.setChunkContent(content);
//                        chunk.setChunkOrder(chunkOrder++);
//                        qaRecordChunkMapper.insert(chunk);
                    }
                } catch (Exception e) {
                    // 解析失败继续处理下一个数据块
                    continue;
                }
            }
        }

        return fullResponse.toString();
    }

    /**
     * 从流式数据中提取内容
     */
    private String parseContentFromStreamData(JSONObject jsonObject) {
        // 新格式：content数组
        if (jsonObject.containsKey("content")) {
            JSONArray contentArray = jsonObject.getJSONArray("content");
            StringBuilder contentBuilder = new StringBuilder();

            for (int i = 0; i < contentArray.size(); i++) {
                JSONObject contentObj = contentArray.getJSONObject(i);
                if (contentObj.containsKey("text")) {
                    JSONObject textObj = contentObj.getJSONObject("text");
                    if (textObj.containsKey("value")) {
                        contentBuilder.append(textObj.getString("value"));
                    }
                }
            }

            return contentBuilder.toString();
        }

        return "";
    }
}
